//
//  WXLListenGoodSoundViewController.m
//  段子手
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 JokesTeam. All rights reserved.
//

#import "WXLListenGoodSoundViewController.h"

@interface WXLListenGoodSoundViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, WXLCollectionReusableViewDelegate, WXLAllBothListenCollectionViewCellDelegate, WXLEveryCollectionReusableViewDelegate>

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, strong) UIVisualEffectView *visualEfView; /**< 毛玻璃 */

@property (nonatomic, retain) NSMutableArray *dataArr; /**< 数据处理结果数组 */


@property (nonatomic, retain) UIImageView *imgView; /**< 播放旋转小图 */
@property (nonatomic, retain) TouchMoveView *touchMovieView;
@property (nonatomic, retain) CABasicAnimation *animation; /**< 动画 */
@property (nonatomic, retain) UIButton *button; /**< 旋转上的小button */

@property (nonatomic, retain) WXLSongsModel *myModel; /** 用来传值 改变 下一页 小动画 */

@property (nonatomic, assign) BOOL isPlay;

@end

@implementation WXLListenGoodSoundViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dataArr = [NSMutableArray new];
        self.isPlay = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.translucent = NO;
    // navbar的控件颜色
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.42 green:0.33 blue:0.28 alpha:1];
    // navbar的背景颜色
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:1 green:0.87 blue:0.68 alpha:1];
    
    self.navigationItem.title = @"好声";
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"beijing.jpg"]];
    
//    [PlayMusic shareMusic].delegate = self;
    
    // 数据请求 与处理
    [self dataHandelFromUrl];
    
    // 创建子视图
    [self createSubView];
    
    [self addHeader];
}



#pragma mark - 创建子视图
- (void)createSubView {
    
    // 毛玻璃
    [self createVisualEfView];
    
    // 创建collectionView
    [self createCollectionView];
 
    // 创建可拖动的view
    [self createTouchMoveView];
    
    [self createAnimationView];
    
    [self createRightSearchItem];
}

- (void)createRightSearchItem {
    UIBarButtonItem *rightSearchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(rightSearchItemAction:)];
    self.navigationItem.rightBarButtonItem = rightSearchItem;
}

/** 创建可拖动的view */
- (void)createTouchMoveView {
    
    self.touchMovieView = [[TouchMoveView alloc] initWithFrame:CGRectMake(kUIScreenWidth - 65, kUIScreenHeight - 178, 60, 60)];
    [self.view addSubview:_touchMovieView];
    
}

- (void)createAnimationView {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeMusic:) name:@"changeSongs" object:nil];
    
    self.imgView = [[UIImageView alloc] init];
    _imgView.frame = CGRectMake(5, 5, _touchMovieView.frame.size.width - 10, _touchMovieView.frame.size.height - 10);
    [self.touchMovieView addSubview:_imgView];
    _imgView.layer.cornerRadius = _imgView.frame.size.height / 2;
    _imgView.layer.masksToBounds = YES;
    _imgView.userInteractionEnabled = YES;
    _imgView.image = [UIImage imageNamed:@"beijing.jpg"];
    
    self.button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self.imgView addSubview:_button];
    _button.frame = CGRectMake((_imgView.frame.size.width - 20) / 2, (_imgView.frame.size.height - 20) / 2, 20, 20);
    _button.layer.cornerRadius = 10;
    _button.layer.masksToBounds = YES;
    _button.backgroundColor = [UIColor whiteColor];
    [_button setTitle:@"播" forState:(UIControlStateNormal)];
    [_button setTitleColor:[UIColor blackColor]forState:(UIControlStateNormal)];
    [_button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    // 保证安全
    if (!self.animation) {
        // CALayer 动画
        // Core Animtion
        self.animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    }
    // 旋转的起始值
    _animation.fromValue = [NSNumber numberWithFloat:0];
    // 旋转的结束值
    // π 是 180°  2π 是 360°
    _animation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    // 重复次数
    _animation.repeatCount = NSIntegerMax;
    // 时间
    _animation.duration = 5;
    // 是否自动回到原来位置
    _animation.autoreverses = NO;
    // 是否按照结束位置继续旋转
    _animation.cumulative = YES;
    
    [_imgView.layer addAnimation:_animation forKey:@"标记"];
    
}

/** 创建collectionView */
- (void)createCollectionView {

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight - 113) collectionViewLayout:flowLayout];
    [self.view addSubview:_collectionView];
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor clearColor];
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    // 注册cell重用池
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [_collectionView registerClass:[WXLAllBothListenCollectionViewCell class] forCellWithReuseIdentifier:@"WXLAllBothListenCollectionViewCell"];
    [_collectionView registerClass:[WXLTypeIsTwoCollectionViewCell class] forCellWithReuseIdentifier:@"WXLTypeIsTwoCollectionViewCell"];
    [_collectionView registerClass:[WXLStypeIsTwoCollectionViewCell class] forCellWithReuseIdentifier:@"WXLStypeIsTwoCollectionViewCell"];
    
    // 注册头视图
    [_collectionView registerClass:[WXLCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"WXLCollectionReusableView"];
    [_collectionView registerClass:[WXLEveryCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"WXLEveryCollectionReusableView"];
    
    
}

// 毛玻璃
- (void)createVisualEfView {
    // 毛玻璃
    self.visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    _visualEfView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    _visualEfView.alpha = 1;
    _visualEfView.userInteractionEnabled = YES;
    
    [self.view addSubview:_visualEfView];
    [self.touchMovieView addSubview:_visualEfView];
}



#pragma mark - collectionView Delegate & DataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    WXLDataModel *model = _dataArr[section + 2];
   
    if ([model.style isEqualToString:@"14"]) {
        
        NSArray *arr = model.dataArr;
        
        WXLActionModel *aModel = [WXLActionModel modelWithDic:nil];
        if (arr.count) {
            aModel = arr[0];
        }
        NSArray *songsArr = aModel.songsModelArr;
        
        return songsArr.count;
    } else if ([model.style isEqualToString:@"5"]) {
        
        NSArray *arr = model.dataArr;
        return arr.count;
    } else if ([model.style isEqualToString:@"2"]) {
        
        NSArray *arr = model.dataArr;
        return arr.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
   
    WXLDataModel *model = _dataArr[indexPath.section + 2];
    if ([model.style isEqualToString:@"14"]) {
        WXLAllBothListenCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WXLAllBothListenCollectionViewCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
       
        cell.delegate = self;
        cell.indexPath = indexPath;
        NSArray *arr = model.dataArr;
        
        WXLActionModel *aModel = [WXLActionModel modelWithDic:nil];
        if (arr.count) {
            aModel = arr[0];
        }
        NSArray *songsArr = aModel.songsModelArr;

        
        cell.model = songsArr[indexPath.row];
        
        return cell;
    } else if ([model.style isEqualToString:@"5"]) {
        
        WXLTypeIsTwoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WXLTypeIsTwoCollectionViewCell" forIndexPath:indexPath];
        
        NSArray *arr = model.dataArr;
        
        WXLActionModel *actionModel = arr[indexPath.row];
        cell.model = actionModel;
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    } else if ([model.style isEqualToString:@"2"]) {
        WXLStypeIsTwoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WXLStypeIsTwoCollectionViewCell" forIndexPath:indexPath];
        NSArray *arr = model.dataArr;
        cell.model = arr[indexPath.row];
        
        return cell;
    }
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];
    return cell;
}

// 返回分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _dataArr.count - 2;
}

// 返回cell大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    WXLDataModel *model = _dataArr[indexPath.section + 2];
    if ([model.style isEqualToString:@"14"]) {
        return CGSizeMake(kUIScreenWidth - 20, 80);
    } else if ([model.style isEqualToString:@"5"]) {
        return CGSizeMake((kUIScreenWidth - 41) / 3, (kUIScreenWidth - 41) / 3 + 40);
    } else if ([model.style isEqualToString:@"2"]) {
        return CGSizeMake(kUIScreenWidth - 20, (kUIScreenWidth - 41) / 3.5);
    }
    return CGSizeMake(0, 0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
   
    WXLDataModel *model = _dataArr[indexPath.section + 2];
    // 如果是第一个分区
    if ([model.style isEqualToString:@"14"]) {

        NSArray *arr = model.dataArr;
        if (!arr.count) {
            return;
        }
        WXLActionModel *aModel = arr[0];;
        
        NSArray *songsArr = aModel.songsModelArr;
        
        [PLAYMUSIC playMusicWithAvUrl:songsArr dex:indexPath.row];
        
        [PLAYMUSIC startPlay];
       
        WXLSongsModel *sModel = songsArr[indexPath.row];
        [_imgView HANDLEIMAGE(sModel.picUrl)];
    }
    // 如果style是 5
    if ([model.style isEqualToString:@"5"]) {
        if (![model.ID_data isEqualToString:@"2892"] && ![model.ID_data isEqualToString:@"2891"]) {
            WXLSongsListCellViewController *wxlSLCVC = [[WXLSongsListCellViewController alloc] init];
            wxlSLCVC.myModel = _myModel;
            WXLActionModel *aModel = model.dataArr[indexPath.row];

            wxlSLCVC.strID = aModel.value;
            
            [self presentViewController:wxlSLCVC animated:YES completion:nil];
        }
    }
}

// 返回头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        // 如果是第一个分区
        if (indexPath.section == 0) {
            WXLCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"WXLCollectionReusableView" forIndexPath:indexPath];
            header.backgroundColor = [UIColor clearColor];
            
            // 指定代理人
            header.delegate = self;
            
            // 确保安全
            if (_dataArr.count) {
                
                header.model = _dataArr[0];
                
            }
            if (_dataArr.count >= 2) {
                
                header.fourModel = _dataArr[1];
            }
            return header;
        }
        // 如果不是第一个分区
        WXLEveryCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"WXLEveryCollectionReusableView" forIndexPath:indexPath];
        
        header.backgroundColor = [UIColor clearColor];
        header.delegate = self;
        header.indexPath = indexPath;
        header.model = _dataArr[indexPath.section + 2];
        
        return header;
    }
    return nil;
}

// 返回头视图高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGSizeMake(kUIScreenWidth, kUIScreenHeight / 4 + 70);
    }
    return CGSizeMake(kUIScreenWidth, 60);
}



#pragma mark = WXLCollectionReusableViewDelegate
- (void)cellClick:(NSIndexPath *)indexpath {
    if (indexpath.row == 0) {
        WXLMoreMusicViewController *MMVC = [[WXLMoreMusicViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:MMVC];
        
        MMVC.myModel = _myModel;
        [self presentViewController:nav animated:YES completion:nil];
    } else if (indexpath.row == 1) {
        WXLSongsListViewController *wxlSLVC = [[WXLSongsListViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:wxlSLVC];
        wxlSLVC.myModel = _myModel;
        [self presentViewController:nav animated:YES completion:nil];
    }
}



#pragma mark - WXLHotSongsTableViewCellDelegate
- (void)mVButtonAtionClick:(WXLSongsModel *)songsModel {
    
    WXLPLAYVIDEO.songsModel = songsModel;
    
    [PLAYMUSIC pausePlay];
    
    [self presentViewController:WXLPLAYVIDEO animated:YES completion:nil];
}



#pragma mark - WXLEveryCollectionReusableViewDelegate
- (void)moreButtonActionClick:(NSInteger)section {
    NSLog(@"%ld", section);
    if (section == 1) {
        WXLSongsListViewController *wxlSLVC = [[WXLSongsListViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:wxlSLVC];
        wxlSLVC.myModel = _myModel;
        [self presentViewController:nav animated:YES completion:nil];
    }
}




#pragma mark - 接到通知 执行该方法
- (void)changeMusic:(NSNotification *)notification {
//    self.navigationItem.title = notification.object;
    WXLSongsModel *model = notification.object;
    
    _myModel = model;
    if (!model.picUrl.length) {
        return;
    }
    [_imgView HANDLEIMAGE(model.picUrl)];
}



#pragma mark - 数据处理
- (void)dataHandelFromUrl {
    
    [WxlAPPTools GETWithURL:@"http://api.dongting.com/frontpage/frontpage?v=v8.4.0.2016022715&f=f168&s=s200&version=0" par:nil success:^(id responseObject) {
        
        NSArray *tempArr = [WXLHomeMusicDataModel modelWithDic:responseObject].dataModelArr;
        
        // 为了安全
        if (!tempArr.count) {
            return;
        }
        
        if (_dataArr.count) {
            [_dataArr removeAllObjects];
        }
        
        for (WXLDataModel *model in tempArr) {
            [_dataArr addObject:model];
        }
        
        [_collectionView reloadData];
        [_collectionView.mj_header endRefreshing];
        
    } filed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    
    
}



#pragma mark - 下拉刷新
- (void)addHeader {

    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandelFromUrl)];
    
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    // 设置文字
    [header setTitle:@"刷新完成" forState:MJRefreshStateIdle];
    [header setTitle:@"开始刷新" forState:MJRefreshStatePulling];
    [header setTitle:@"正在刷新 ..." forState:MJRefreshStateRefreshing];
    
    // 设置字体
    header.stateLabel.font = [UIFont systemFontOfSize:15];
    header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    
    // 设置颜色
    header.stateLabel.textColor = [UIColor redColor];
    header.lastUpdatedTimeLabel.textColor = [UIColor blueColor];
    
    
    _collectionView.mj_header = header;
    
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
    
    // 保证安全
    if (!self.animation) {
        self.animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    }
    // 旋转的起始值
    _animation.fromValue = [NSNumber numberWithFloat:0];
    // 旋转的结束值
    // π 是 180°  2π 是 360°
    _animation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    // 重复次数
    _animation.repeatCount = NSIntegerMax;
    // 时间
    _animation.duration = 5;
    // 是否自动回到原来位置
    _animation.autoreverses = NO;
    // 是否按照结束位置继续旋转
    _animation.cumulative = YES;
    
    [_imgView.layer addAnimation:_animation forKey:@"标记"];
    
}



#pragma mark - button点击方法
- (void)rightSearchItemAction:(UIBarButtonItem *)item {
    WXLSearchViewController *wxlSVC = [[WXLSearchViewController alloc] init];
    wxlSVC.myModel = _myModel;
    
    __weak typeof(WXLSearchViewController) *weakVC = wxlSVC;
    wxlSVC.blockChangeImage = ^(NSString *pic){
        [weakVC.imgView HANDLEIMAGE(pic)];
    };
    wxlSVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:wxlSVC animated:YES];
}

- (void)buttonAction:(UIButton *)button {
    if ([button.titleLabel.text isEqualToString:@"单"]) {
        WXLMoreMusicViewController *MMVC = [[WXLMoreMusicViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:MMVC];
        
        [self presentViewController:nav animated:YES completion:nil];
        
    } else if ([button.titleLabel.text isEqualToString:@"播"]) {
        
        [self presentViewController:[WXLPlayMusicViewController shareWXLPlayMusicViewController] animated:YES completion:nil];
        
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
